package com.liyuan.yiqixing.service.impl;

import com.liyuan.yiqixing.dao.AuthenticationDao;
import com.liyuan.yiqixing.dao.DiscussionDao;
import com.liyuan.yiqixing.model.Discussion;
import com.liyuan.yiqixing.model.User;
import com.liyuan.yiqixing.service.DiscussionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class DiscussionServiceImpl implements DiscussionService {
    @Autowired
    SimpleDateFormat simpleDateFormat;
    @Autowired
    DiscussionDao discussionDao;
    @Autowired
    AuthenticationDao authenticationDao;
    @Override
    public Discussion[] retrieveDiscussions(Integer currentPage, Integer scale, String classification) {
        Discussion[] discussions = discussionDao.selectDiscussions((currentPage - 1) * scale, scale, classification);
        for(int i=0;i<discussions.length;i++){
            completeUserInfo(discussions[i]);
        }
        return discussions;
    }

    @Override
    public int sum(String classification) {
        return discussionDao.sum(classification);
    }

    @Override
    public Discussion retrieveDiscussion(Integer id) {
        Discussion discussion = discussionDao.selectDiscussion(id);
        completeUserInfo(discussion);
        return discussion;
    }

    private void completeUserInfo(Discussion discussion) {
        User user = authenticationDao.retrieveUserById(discussion.getUser().getId());
        discussion.getUser().setAvatarUrl(user.getAvatarUrl());
        discussion.getUser().setRole(user.getRole().getId());
        discussion.getUser().setNickname(user.getNickname());
        discussion.getUser().setLevel(user.getLevel());
        discussion.getUser().setDescription(user.getDescription());
    }

    @Override
    public void saveDiscussion(Discussion discussion) {
        discussion.setModifiedAt(simpleDateFormat.format(new Date()));
        discussionDao.insertDiscussion(discussion);
    }

    @Override
    public int selectLastInsertId() {
        return discussionDao.selectLastInsertId();
    }
}
